package com.nobody.facepk.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.nobody.facepk.pojo.SessionUserLocal;
import com.nobody.facepk.service.ServiceRegistry;

/**
 * 判断玩家是否已经登录，如果未登录则跳转到登陆页面
 * 
 * @author wangjun
 * 
 */
public class ScoreInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = Logger.getLogger(ScoreInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(!ServiceRegistry.getPictureManager().isEmpty() && request.getMethod().equalsIgnoreCase("get")) {
			Long pictureId = ServiceRegistry.getPictureManager().getRandomPicture();
			String url = request.getRequestURI();
			String queryString = request.getQueryString();
			if(queryString!=null) url = url +"?"+queryString;
			request.setAttribute("NEXT_URL", url);
			response.sendRedirect("vote.jsp?pictureId="+pictureId);
			return false;
		}
		else return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		SessionUserLocal.clear();
		super.afterCompletion(request, response, handler, ex);
	}
}
